require 'base64'
require 'openssl'

class InitSessionController < ApplicationController
  def signin
    logger.debug "*******Starting logging controller"
    logger.debug "******* params[:commit]=#{params[:commit]}"
    if (params[:commit]=="Sign In")
      logger.debug "signing in";
      sha512=OpenSSL::Digest::SHA512.new
      password = params[:user]
      password = password[:password]
      sha512.update(password)
      password_digest = Base64.encode64(sha512.digest.to_s)
      current_user = MwUser.where('user_name = ?', params[:userName]).first
      if(current_user.respond_to? :user_name)
        logger.debug "current_user=#{current_user}"
        logger.debug "current_user.user_name=#{current_user.user_name}"
        logger.debug "current_user.password=#{current_user.password}"
        if current_user.password == password_digest
          redirect_to :controller => "session_init", :action =>"redirect" ,:rol => MwCatalogRol.find(current_user.MW_Catalog_Rol_id).rol_name
        else
          redirect_to :action => "signin", :logError => "Wrong password", :reload_username => params[:userName]
        end
      else
        redirect_to :action => "signin", :logError =>"Your user name is not registered"
      end
    end
  end


  def register
    @rols = MwCatalogRol.all
    @rolsArray = Array.new
    for rolData in @rols
      @rolsArray.push [rolData.rol_name, rolData.id]
    end
    if (params[:commit]=="Register")
      allUsers = MwUser.all
      @user = MwUser.new()
      sha512=OpenSSL::Digest::SHA512.new
      password = params[:user]
      password = password[:password]
      sha512.update(password)
      @user.password=Base64.encode64(sha512.digest.to_s)
      @user.user_name=params[:userName]
      @user.MW_Catalog_Rol_id=params[:rol]
      @profile =MwProfile.new
      @profile.address = params[:address]
      @profile.phone = params[:phone]
      @profile.mail = params[:mail]
      isUserAlreadyInDatabase = false
      allUsers.each do |individualUser|
        if(individualUser.user_name == @user.user_name)
          isUserAlreadyInDatabase = true
        end
      end
      if (@user.password != nil && @user.user_name != nil && !isUserAlreadyInDatabase)
        @profile.save
        @profile = MwProfile.last
        logger.info "profile id: #{@profile.id}"
        @user.MW_Profile_id=@profile.id
        @user.save
        redirect_to :controller => "init_session", :action => "register_success"
      else
        if(isUserAlreadyInDatabase)
          redirect_to :controller => "init_session", :action => "register", :msgError=> "Usuario en uso"
        elsif(@user.user_name== nil)
          redirect_to :controller => "init_session", :action => "register", :msgError=> "Nombre de usuario invalido"
        elsif(@user.password== nil)
          redirect_to :controller => "init_session", :action => "register", :msgError=> "Clave de acceso invalida"
        end

      end
    end

  end
  def register_success

  end
end

